package com.example.retrofit;

import android.app.Application;
import android.util.Log;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class BaseApplicatiopn extends Application {
    private static final String TAG = "tag";
    public static   WeatherRequest weatherRequest;
    Retrofit ret;

    @Override
    public void onCreate() {
        super.onCreate();
        initRetrofit();
    }
    private void initRetrofit(){
         ret=new Retrofit.Builder().baseUrl("http://apis.juhe.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .callTimeout(5,TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                            @Override
                            public Response intercept(Chain chain) throws IOException {
                                Request request=chain.request();

                              String url= request.url().url().toString();
                              if (null!=request.body()) {
                                  String type = request.body().contentType().type();
                                  String param = request.body().toString();
                                  Log.d(TAG, " 请求类型: "+type);
                                  Log.d(TAG, " 请求参数: "+param);
                              }

                                Response response= chain.proceed(request);
                                String result=response.body().string();
                                Log.d(TAG, " 请求地址: "+url);
                                Log.d(TAG, " 返回数据: "+result);
//                                  重构返回数据
                                return response.newBuilder()
                                        .body(ResponseBody.create(response.body().contentType(), result))
                                        .build();
                            }
                        }).build())
                .build();
        initRequest();
    }
private void initRequest(){
        weatherRequest=ret.create(WeatherRequest.class);
}

}
